<script setup>
import api from '../api/users_api.js'
import {ref, onMounted} from 'vue'
import {ElMessageBox, ElMessage} from 'element-plus'
import lodash from 'lodash'

// 表格数据
const tableData = ref([])
const total = ref(0)

// 查询参数
const searchObj = ref({
  current: 1,
  limit: 10,
  username: '',
  realName: ''
})

// 编辑/新增对象
const obj = ref({})
const editWinVisible = ref(false)

// 页面加载后挂载数据
onMounted(async () => {
  await search()
})

// 查询方法
const search = async () => {
  try {
    const res = await api.page(searchObj.value)
    tableData.value = res.data || []
    total.value = res.count || 0
  } catch (error) {
    console.error(error)
    tableData.value = []
    total.value = 0
  }
}

// 新增用户对象
const newUser = ref({})

// 控制新增对话框显示
const addWinVisible = ref(false)

const showAddDialog = () => {
  newUser.value = {}
  addWinVisible.value = true
}

const addCancel = () => {
  newUser.value = {}
  addWinVisible.value = false
}

// 提交新增
const addCommit = async () => {
  try {
    // **去掉 param 包装**
    await api.add({...newUser.value})
    ElMessage({message: '新增成功', type: 'success'});
    await search();
    addWinVisible.value = false;
  } catch (error) {
    console.error(error);
    ElMessage({message: '新增失败', type: 'error'});
  }
};

// 查询按钮点击
const handleSearch = () => {
  searchObj.value.current = 1
  search()
}

// 分页事件
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  search()
}

const handleCurrentChange = (val) => {
  searchObj.value.current = val
  search()
}

// 取消编辑
const editCancel = () => {
  obj.value = {}
  editWinVisible.value = false
}

// 提交编辑
const editCommit = async () => {
  try {
    // **直接传 obj.value，不再包装**
    await api.edit(obj.value)
    editWinVisible.value = false
    await search()
    ElMessage({message: '修改成功', type: 'success'})
  } catch (error) {
    console.error(error)
    ElMessage({message: '修改失败', type: 'error'})
  }
}

// 编辑按钮点击
const handleEdit = (index, row) => {
  obj.value = lodash.cloneDeep(row)
  editWinVisible.value = true
}


// 新增用户上传成功
const handleAddUploadSuccess = (response, file) => {
  newUser.value.photo = response.data; // 确保设置的是 photo 字段
  console.log('新增用户头像上传成功:', response.data);
}

// 编辑用户上传成功
const handleEditUploadSuccess = (response, file) => {
  obj.value.photo = response.data; // 确保设置的是 photo 字段
  console.log('编辑用户头像上传成功:', response.data);
}


</script>

<template>
  <div style="padding: 20px;">
    <h2>管理员列表</h2>

    <!-- 查询框 -->
    <el-form :inline="true" :model="searchObj" style="margin-bottom: 10px;">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable/>
      </el-form-item>
      <el-form-item label="真实姓名">
        <el-input v-model="searchObj.realName" placeholder="请输入真实姓名" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
<!--        <el-button type="primary" @click="showAddDialog">新增用户</el-button>-->
      </el-form-item>
    </el-form>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="addWinVisible" title="新增用户" width="500">
      <el-form :model="newUser" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="newUser.username"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="newUser.realName"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="newUser.phone"/>
        </el-form-item>
        <el-form-item label="所在学校">
          <el-input v-model="newUser.school"/>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="newUser.studentId"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="newUser.email"/>
        </el-form-item>
        <!-- 新增用户对话框中的头像上传 -->
        <el-form-item label="用户头像">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleAddUploadSuccess"
          >
            <img v-if="newUser.photo" :src="newUser.photo" style="width: 100px; height: 100px"/>
            <img v-else src="@/assets/sc.png" style="width:100px" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addCancel">取消</el-button>
          <el-button type="primary" @click="addCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户表格 -->
    <el-table :data="tableData" border style="width: 100%;">

      <el-table-column prop="userId" label="管理员ID" width="120"/>
      <el-table-column prop="username" label="管理员用户名" width="120"/>
      <el-table-column prop="realName" label="真实姓名" width="120"/>
      <el-table-column prop="phone" label="手机号" width="120"/>
      <el-table-column prop="school" label="所在学校" width="150"/>
      <el-table-column prop="studentId" label="学号" width="120"/>
      <el-table-column prop="email" label="邮箱" width="120"/>
      <el-table-column prop="createTime" label="注册时间" width="180"/>
<!--      <el-table-column label="操作" fixed="right" width="150">-->
<!--        <template #default="scope">-->
<!--          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->

<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="photo" label="用户头像" width="120">
        <template #default="scope">
          <img :src="scope.row.photo || 'src/assets/dephoto.png'" style="width: 100px; height: 100px;"/>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :total="total"
        :page-sizes="[10,20,30,40]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑用户" width="500">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="obj.username" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="obj.realName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="obj.phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="所在学校">
          <el-input v-model="obj.school" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="obj.studentId" autocomplete="off"/>
        </el-form-item>
        <!-- 编辑用户对话框中的头像上传 -->
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleEditUploadSuccess"
          >
            <img v-if="obj.photo" :src="obj.photo" style="width: 100px; height: 100px"/>
            <img v-else src="@/assets/sc.png" style="width:100px" />
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
h2 {
  color: rgba(244, 64, 64, 0.35);
  margin-bottom: 20px;
}
</style>
